package com.sinsoft.monitorDemo.dao;

import java.util.ArrayList;
import java.util.List;

import redis.clients.jedis.Jedis;

import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.sinsoft.monitorDemo.entity.ProcessInfo;
import com.sinsoft.monitorDemo.util.JsonUtil;
import com.sinsoft.monitorDemo.util.RedisUtil;

public class ProcessInfoDao {
	/**
	 * 通过IP的到进程信息
	 * @param ip
	 * @param index
	 * @return
	 */
	public List<ProcessInfo> getProcessInfoList(String ip){
		Jedis jedis = RedisUtil.getJedis();
		List<String> jsonList = jedis.lrange("StatusData_" + ip + "_PROC_latest", 0, -1);
		JsonArray jsonArray = null;
		JsonObject jsonObject = null;
		ProcessInfo processInfo = null;
		List<ProcessInfo> processInfoList = new ArrayList<ProcessInfo>();
		if (jsonList.size()>10) {
			for (int i = jsonList.size()-10; i < jsonList.size(); i++) {
				jsonArray = JsonUtil.JsonParse(jsonList.get(i));
				jsonObject = jsonArray.get(0).getAsJsonObject();
				processInfo = new ProcessInfo(jsonObject.get("process_current").getAsInt(),jsonArray.get(1).getAsLong());
				processInfoList.add(processInfo);
			}			
		} else {
			for (int i = 1; i < jsonList.size(); i++) {
				jsonArray = JsonUtil.JsonParse(jsonList.get(i));
				jsonObject = jsonArray.get(0).getAsJsonObject();
				processInfo = new ProcessInfo(jsonObject.get("process_current").getAsInt(),jsonArray.get(1).getAsLong());
				processInfoList.add(processInfo);
			}
		}
		jedis.close();
		return processInfoList;		
	}
	
	/**
	 * 得到最新的进程信息
	 * @param ip
	 * @return
	 */
	public ProcessInfo getNewProcessInfo(String ip){
		Jedis jedis = RedisUtil.getJedis();
		ProcessInfo processInfo;
		try {
			List<String> jsonList = jedis.lrange("StatusData_" + ip + "_PROC_latest", -1, -1);
				JsonArray jsonArray = JsonUtil.JsonParse(jsonList.get(0));
				JsonObject jsonObject = jsonArray.get(0).getAsJsonObject();
				processInfo = new ProcessInfo(jsonObject.get("process_current").getAsInt(),
						jsonArray.get(1).getAsLong());
		} catch (Exception e) {
			return new ProcessInfo(null, null);
		}finally{
			jedis.close();			
		}
			return processInfo;		
	}

}
